<template>
  <div>
    <el-card class="box-card">
      <!-- 卡片顶部添加品牌按钮 -->
      <el-button type="primary" icon="Plus" @click="addTrademark">
        添加品牌
      </el-button>
      <!-- 表格组件，用于展示已有的品牌信息 -->
      <el-table style="margin: 10px 0" border stripe :data="trademarkArr">
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="100px"
        ></el-table-column>
        <!--      <el-table-column-->
        <!--        label="品牌名称"-->
        <!--        align="center"-->
        <!--        prop="tmName"-->
        <!--      ></el-table-column>-->
        <el-table-column label="品牌名称" align="center">
          <template #default="{ row }">
            <pre style="color: #1087d1; font-weight: bold">{{
              row.tmName
            }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="品牌LOGO" align="center">
          <template #default="{ row }">
            <img
              :src="
                /^http:\/\//.test(row.logoUrl)
                  ? row.logoUrl
                  : 'http://' + row.logoUrl
              "
              alt="品牌logo"
              width="120px"
              height="100px"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
        ></el-table-column>
        <el-table-column
          label="修改时间"
          align="center"
          prop="updateTime"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="250px">
          <template #default="{ row }">
            <el-button type="warning" icon="Edit" @click="updateTrademark(row)">
              修改
            </el-button>
            <el-popconfirm
              :title="`确定要删除${row.tmName}品牌吗？`"
              width="250"
              icon="Delete"
              @confirm="deleteTrademark(row.id)"
            >
              <template #reference>
                <el-button type="danger" icon="Delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :small="false"
        :disabled="false"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 对话框组件，在添加和修改品牌信息时作为弹出框使用 -->
    <el-dialog v-model="dialogFormVisible" :title="dialogFormTitle" draggable>
      <el-form
        class="dialog_form"
        label-width="100px"
        label-position="left"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            v-model="trademarkParams.tmName"
            placeholder="请输入品牌名称"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- action 图片上传路径要加上 /api 否则代理服务器不发送上传的 post 请求 -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="
                /^http:\/\//.test(trademarkParams.logoUrl)
                  ? trademarkParams.logoUrl
                  : 'http://' + trademarkParams.logoUrl
              "
              class="avatar"
              alt="品牌logo"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 footer -->
      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" @click="cancel">取消</el-button>
          <el-button type="primary" @click="confirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 引入组合式API函数 ref
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqHasTrademark,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from '@/api/product/trademark'
import {
  Records,
  TrademarkResponseData,
  Trademark,
} from '@/api/product/trademark/type'
import { Plus } from '@element-plus/icons-vue'
import { ElForm, ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'

// 当前页码
let currentPage = ref<number>(1)
// 每页条数
let pageSize = ref<number>(5)
// 品牌数据总数
let total = ref<number>(0)
// 品牌数据信息
let trademarkArr = ref<Records>([])
// 对话框组件显示状态，控制对话框组件的显示和隐藏
let dialogFormVisible = ref<boolean>(false)
// 对话框组件显示的标题
let dialogFormTitle = ref<string>('添加品牌')
// 定义新增品牌的表单数据
let trademarkParams = reactive<Trademark>({
  tmName: '',
  logoUrl: '',
})

// 获取组件实例
const formRef = ref<InstanceType<typeof ElForm>>()

// 品牌名称的自定义校验规则
const validatorTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('品牌名称至少为2个字符'))
  }
}

// 品牌LOGO的自定义校验规则
const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  // value 为图片上传成功之后的 图片的 URL
  if (value) {
    callback()
  } else {
    callback(new Error('请务必上传品牌LOGO'))
  }
}

// 表单校验规则对象
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatorTmName }],
  logoUrl: [{ required: true, trigger: 'blur', validator: validatorLogoUrl }],
}

// 图片文件上传成功时的钩子
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  trademarkParams.logoUrl = response.data
  // 图片上传成功要清除掉图片校验未通过时候的提示信息
  formRef.value?.clearValidate('logoUrl')
}

// 图片上传文件之前的钩子，钩子在图片上传之前触发，可以约束图片格式和大小，返回 false 则停止上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type === 'image/jpeg' ||
    rawFile.type === 'image/png' ||
    rawFile.type === 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage.error('图片大小不能超过4MB!!')
      return false
    }
  } else {
    ElMessage.error('图片必须是JPG格式/PNG格式/GIF格式!!')
    return false
  }
}

// 获取品牌列表数据
const getHasTrademark = async (page = 1) => {
  currentPage.value = page
  let result: TrademarkResponseData = await reqHasTrademark(
    currentPage.value,
    pageSize.value,
  )
  if (result.code === 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}

// 组件挂在完毕获取品牌列表数据
onMounted(() => {
  getHasTrademark()
})

// 分页器每页条数发生改变的时候触发
const handleSizeChange = () => {
  getHasTrademark()
}

// 分页器当前页码发生改变的时候触发
const handleCurrentChange = (val: number) => {
  getHasTrademark(val)
}

// 添加品牌按钮点击事件
const addTrademark = () => {
  trademarkParams.tmName = ''
  trademarkParams.logoUrl = ''
  trademarkParams.id = undefined
  dialogFormTitle.value = '添加品牌'
  dialogFormVisible.value = true
  // 清除上一次表单校验未通过时候的提示信息
  // 方式一： ? 可选链式操作
  // formRef.value?.clearValidate()
  // 方式二： 使用 nextTick()
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

// 修改品牌按钮点击事件
const updateTrademark = (row: Trademark) => {
  // 清除上一次表单校验未通过时候的提示信息
  // 方式一： ? 可选链式操作
  // formRef.value?.clearValidate()
  // 方式二： 使用 nextTick()
  nextTick(() => {
    formRef.value.clearValidate()
  })
  dialogFormTitle.value = '修改品牌'
  dialogFormVisible.value = true
  // ES6语法合并对象
  Object.assign(trademarkParams, row)
  // trademarkParams.id = row.id
  // trademarkParams.tmName = row.tmName
  // trademarkParams.logoUrl = row.logoUrl
}

// 删除品牌按钮气泡框确认点击事件
const deleteTrademark = async (id: number) => {
  let result = await reqDeleteTrademark(id)
  if (result.code === 200) {
    ElMessage.success('删除品牌成功!')
  } else {
    ElMessage.error('删除品牌失败!')
  }
  await getHasTrademark(
    currentPage.value === 1
      ? currentPage.value
      : trademarkArr.value.length > 1
      ? currentPage.value
      : currentPage.value - 1,
  )
}

// 弹出框确定按钮点击事件
const confirm = async () => {
  // 表单提交之前校验整个表单的验证规则
  await formRef.value?.validate()
  let result = await reqAddOrUpdateTrademark(trademarkParams)
  if (result.code === 200) {
    ElMessage.success(dialogFormTitle.value + '成功!')
  } else {
    ElMessage.error(dialogFormTitle.value + '失败!')
  }
  dialogFormVisible.value = false
  await getHasTrademark(trademarkParams.id ? currentPage.value : 1)
}

// 弹出框取消按钮点击事件
const cancel = () => {
  dialogFormVisible.value = false
}
</script>

<style scoped>
.dialog_form {
  width: 95%;
  margin: 0 10px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 2px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
